package com.zhaokuner.rabbitmq.boot.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";


    //1.交换机
    @Bean("bootExchange")
    public Exchange bootExchange() {
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
//        return ExchangeBuilder.fanoutExchange(EXCHANGE_NAME).durable(true).build();
    }

    //2.Queue 队列
    @Bean("bootQueue")
    public Queue bootQueue() {
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    //3. 队列和交互机绑定关系 Binding
    /*
        1. 知道哪个队列
        2. 知道哪个交换机
        3. routing key
     */
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
        //  return BindingBuilder.bind(queue).to(exchange).with("").noargs();
        return BindingBuilder.bind(queue).to(exchange).with("info.#").noargs();
    }

    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback(RabbitTemplate rabbitTemplate) {
        RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
            System.out.println("---ConfirmCallback " + correlationData.getId() + " " + ack + " " + cause);
        };
        rabbitTemplate.setConfirmCallback(confirmCallback);
        return confirmCallback;
    }


    @Bean
    public RabbitTemplate.ReturnsCallback returnCallback(RabbitTemplate rabbitTemplate) {
        RabbitTemplate.ReturnsCallback returnsCallback = (returned) -> {
            System.out.println("---ReturnsCallback " + returned.getExchange() + " " + returned.getRoutingKey() + " " + returned.getReplyCode() + " " + returned.getReplyText());
        };
        rabbitTemplate.setReturnsCallback(returnsCallback);
        rabbitTemplate.setMandatory(true);
        return returnsCallback;
    }
}
